package com.teamwhole.core.persistence;

import java.io.Serializable;
import java.util.Map;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.teamwhole.common.utils.IdGen;
import com.teamwhole.common.utils.StringUtils;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
public abstract class BaseEntity<T> implements Serializable {
	private static final long serialVersionUID = 1L;
	protected String id;
	@JsonIgnore
	protected String delFlag = DEL_FLAG_NORMAL;
	@JsonIgnore
	protected boolean isNewRecord = false;
	@JsonIgnore
	protected Map<String, Object> paramMap = Maps.newHashMap();
	@JsonIgnore
	protected Integer page = 1;
	@JsonIgnore
	protected Integer rows = 20;

	public BaseEntity() {
		this.delFlag = DEL_FLAG_NORMAL;
	}

	public BaseEntity(String id) {
		this();
		this.id = id;
	}

	@JsonIgnore
	public boolean isNewRecord() {
		return isNewRecord || StringUtils.isBlank(getId());
	}

	public void setNewRecord(boolean isNewRecord) {
		this.isNewRecord = isNewRecord;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Map<String, Object> getParamMap() {
		return paramMap;
	}
	@JsonProperty("paramMap")
	public void setParamMap(Map<String, Object> paramMap) {
		this.paramMap = paramMap;
	}
	
	public Integer getPage() {
		return page;
	}
	@JsonProperty("page")
	public void setPage(Integer page) {
		this.page = page;
	}

	public Integer getRows() {
		return rows;
	}
	@JsonProperty("rows")
	public void setRows(Integer rows) {
		this.rows = rows;
	}

	@Override
	public boolean equals(Object obj) {
		if (null == obj) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		if (!getClass().equals(obj.getClass())) {
			return false;
		}
		BaseEntity<?> that = (BaseEntity<?>) obj;
		return null == this.getId() ? false : this.getId().equals(that.getId());
	}

	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}

	public void preInsert() {
		/** 不限制ID为UUID，调用setIsNewRecord()使用自定义ID **/
		// if (!this.isNewRecord){
		setId(IdGen.uuid());
		// }
	}

	public void preUpdate() {

	}

	public void startPage() {
		PageHelper.startPage(this.getPage(), this.getRows());
	}

	/** 删除标记(0:删除;1:正常;) **/
	public static final String DEL_FLAG_NORMAL = "1";
	public static final String DEL_FLAG_DELETE = "0";

}
